<template>
    <div class="register-container">
        <div v-if="isLoading" class="loading-container">
            <div class="loading-spinner"></div>
        </div>
        
        <div v-else class="register-box">
            <div class="logo">
                <img src="https://img1.dxycdn.com/t/s22/2023/1020/192/0844255084588925171.png" alt="丁香医生" class="logo-img" />
                <h2>注册</h2>
            </div>

            <form v-if="isFormReady" @submit.prevent="handleRegister" class="register-form">
                <div class="form-group">
                    <input 
                        type="tel" 
                        v-model="formData.mobile" 
                        placeholder="手机号"
                        class="input-field"
                        maxlength="11"
                        @blur="checkMobile"
                        autocomplete="off"
                    />
                </div>

                <div class="form-group verification-group">
                    <input 
                        type="text" 
                        v-model="formData.sms_code" 
                        placeholder="验证码"
                        class="input-field"
                        maxlength="6"
                        autocomplete="off"
                    />
                    <button 
                        type="button" 
                        class="get-code-btn" 
                        @click="getVerificationCode"
                        :disabled="countdown > 0"
                    >
                        {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
                    </button>
                </div>

                <div class="form-group">
                    <input 
                        :type="showPassword ? 'text' : 'password'" 
                        v-model="formData.password" 
                        placeholder="设置密码"
                        class="input-field"
                        autocomplete="new-password"
                    />
                    <span 
                        class="toggle-password"
                        @click="showPassword = !showPassword"
                        :title="showPassword ? '隐藏密码' : '显示密码'"
                    >
                        <svg v-if="showPassword" class="eye-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 4.5C7 4.5 2.73 7.61 1 12C2.73 16.39 7 19.5 12 19.5C17 19.5 21.27 16.39 23 12C21.27 7.61 17 4.5 12 4.5ZM12 17C9.24 17 7 14.76 7 12C7 9.24 9.24 7 12 7C14.76 7 17 9.24 17 12C17 14.76 14.76 17 12 17ZM12 9C10.34 9 9 10.34 9 12C9 13.66 10.34 15 12 15C13.66 15 15 13.66 15 12C15 10.34 13.66 9 12 9Z" fill="currentColor"/>
                        </svg>
                        <svg v-else class="eye-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 6.5C15.79 6.5 19.17 8.63 20.82 12C19.17 15.37 15.79 17.5 12 17.5C8.21 17.5 4.83 15.37 3.18 12C4.83 8.63 8.21 6.5 12 6.5ZM12 4.5C7 4.5 2.73 7.61 1 12C2.73 16.39 7 19.5 12 19.5C17 19.5 21.27 16.39 23 12C21.27 7.61 17 4.5 12 4.5ZM12 9.5C13.38 9.5 14.5 10.62 14.5 12C14.5 13.38 13.38 14.5 12 14.5C10.62 14.5 9.5 13.38 9.5 12C9.5 10.62 10.62 9.5 12 9.5ZM12 7.5C9.52 7.5 7.5 9.52 7.5 12C7.5 14.48 9.52 16.5 12 16.5C14.48 16.5 16.5 14.48 16.5 12C16.5 9.52 14.48 7.5 12 7.5Z" fill="currentColor"/>
                            <path d="M2 4L22 20" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        </svg>
                    </span>
                </div>

                <div class="form-group">
                    <input 
                        :type="showPassword ? 'text' : 'password'" 
                        v-model="formData.re_password" 
                        placeholder="确认密码"
                        class="input-field"
                        autocomplete="new-password"
                    />
                    <span 
                        class="toggle-password"
                        @click="showPassword = !showPassword"
                        :title="showPassword ? '隐藏密码' : '显示密码'"
                    >
                        <svg v-if="showPassword" class="eye-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 4.5C7 4.5 2.73 7.61 1 12C2.73 16.39 7 19.5 12 19.5C17 19.5 21.27 16.39 23 12C21.27 7.61 17 4.5 12 4.5ZM12 17C9.24 17 7 14.76 7 12C7 9.24 9.24 7 12 7C14.76 7 17 9.24 17 12C17 14.76 14.76 17 12 17ZM12 9C10.34 9 9 10.34 9 12C9 13.66 10.34 15 12 15C13.66 15 15 13.66 15 12C15 10.34 13.66 9 12 9Z" fill="currentColor"/>
                        </svg>
                        <svg v-else class="eye-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 6.5C15.79 6.5 19.17 8.63 20.82 12C19.17 15.37 15.79 17.5 12 17.5C8.21 17.5 4.83 15.37 3.18 12C4.83 8.63 8.21 6.5 12 6.5ZM12 4.5C7 4.5 2.73 7.61 1 12C2.73 16.39 7 19.5 12 19.5C17 19.5 21.27 16.39 23 12C21.27 7.61 17 4.5 12 4.5ZM12 9.5C13.38 9.5 14.5 10.62 14.5 12C14.5 13.38 13.38 14.5 12 14.5C10.62 14.5 9.5 13.38 9.5 12C9.5 10.62 10.62 9.5 12 9.5ZM12 7.5C9.52 7.5 7.5 9.52 7.5 12C7.5 14.48 9.52 16.5 12 16.5C14.48 16.5 16.5 14.48 16.5 12C16.5 9.52 14.48 7.5 12 7.5Z" fill="currentColor"/>
                            <path d="M2 4L22 20" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        </svg>
                    </span>
                </div>

                <div class="agreement">
                    <label class="checkbox-label">
                        <input type="checkbox" v-model="agreed" />
                        <span>我已阅读并接受丁香园</span>
                        <a href="https://3g.dxy.cn/newh5/view/rule/userAgreement" target="_blank" class="link">《用户协议》</a>
                        <a href="https://3g.dxy.cn/newh5/view/rule/privacyPolicy" target="_blank" class="link">《隐私政策》</a>
                    </label>
                </div>

                <button type="submit" class="submit-btn" :disabled="!agreed || loading">
                    {{ loading ? '注册中...' : '注册' }}
                </button>

                <div class="bottom-links">
                    <span>已有账号？</span>
                    <router-link to="/login" class="login-link">马上登录</router-link>
                </div>

                <div class="alternative-register">
                    <router-link to="/register/email" class="email-register">
                        使用邮箱注册
                    </router-link>
                </div>
            </form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const showPassword = ref(false)
const agreed = ref(false)
const loading = ref(false)
const countdown = ref(0)
const isLoading = ref(true)
const isFormReady = ref(false)
let timer: NodeJS.Timer | null = null

const formData = reactive({
    mobile: '',
    sms_code: '',
    password: '',
    re_password: ''
})

const resetForm = () => {
    formData.mobile = ''
    formData.sms_code = ''
    formData.password = ''
    formData.re_password = ''
    agreed.value = false
    showPassword.value = false
    countdown.value = 0
}

onMounted(async () => {
    try {
        await new Promise(resolve => setTimeout(resolve, 500)) // 模拟初始化延迟
        resetForm()
        isFormReady.value = true
    } finally {
        isLoading.value = false
    }
})

const startCountdown = () => {
    countdown.value = 60
    timer = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--
        } else {
            if (timer) {
                clearInterval(timer)
                timer = null
            }
        }
    }, 1000)
}

const checkMobile = async () => {
    if (!formData.mobile) return
    if (!/^1[3-9]\d{9}$/.test(formData.mobile)) {
        ElMessage.warning('请输入正确的手机号')
        return
    }

    try {
        await axios.get(`http://127.0.0.1:8000/user/mobile/${formData.mobile}/`)
        ElMessage.success('手机号可用')
    } catch (error: any) {
        if (error.response?.status === 400) {
            ElMessage.warning('该手机号已被注册')
        }
    }
}

const getVerificationCode = async () => {
    if (!formData.mobile) {
        ElMessage.warning('请输入手机号')
        return
    }
    
    if (!/^1[3-9]\d{9}$/.test(formData.mobile)) {
        ElMessage.warning('请输入正确的手机号')
        return
    }

    try {
        const response = await axios.get(`http://127.0.0.1:8000/user/sendsms/${formData.mobile}/`)
        if (response.status === 200) {
            ElMessage.success('验证码发送成功')
            startCountdown()
        }
    } catch (error: any) {
        ElMessage.error(error.response?.data?.error || '验证码发送失败')
    }
}

const handleRegister = async () => {
    if (!agreed.value) {
        ElMessage.warning('请先同意用户协议和隐私政策')
        return
    }

    if (formData.password !== formData.re_password) {
        ElMessage.error('两次输入的密码不一致')
        return
    }

    try {
        loading.value = true
        const response = await axios.post('http://127.0.0.1:8000/user/register/', formData)
        if (response.status === 201) {
            ElMessage.success('注册成功')
            router.push('/login')
        }
    } catch (error: any) {
        ElMessage.error(error.response?.data?.error || '注册失败')
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
.register-container {
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f5f7fa;
    padding: 20px;
}

.loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #7B66FF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.register-box {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    width: 100%;
    max-width: 400px;
    padding: 32px;
    opacity: 0;
    animation: fadeIn 0.3s ease-out forwards;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.logo {
    text-align: center;
    margin-bottom: 32px;
}

.logo-img {
    height: 40px;
    margin-bottom: 16px;
}

.logo h2 {
    font-size: 24px;
    color: #333;
    margin: 0;
}

.register-form {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.form-group {
    position: relative;
}

.input-field {
    width: 100%;
    padding: 12px 16px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    font-size: 14px;
    transition: all 0.3s;
    background-color: #fff;
}

.input-field:focus {
    border-color: #7B66FF;
    outline: none;
    box-shadow: 0 0 0 2px rgba(123, 102, 255, 0.1);
}

.verification-group {
    display: flex;
    gap: 12px;
}

.get-code-btn {
    white-space: nowrap;
    padding: 0 16px;
    color: #7B66FF;
    background: none;
    border: none;
    cursor: pointer;
    transition: all 0.3s;
}

.get-code-btn:hover:not(:disabled) {
    color: #6B56FF;
}

.get-code-btn:disabled {
    color: #909399;
    cursor: not-allowed;
}

.toggle-password {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    color: #909399;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 4px;
    border-radius: 4px;
    transition: all 0.3s;
}

.toggle-password:hover {
    color: #7B66FF;
    background-color: rgba(123, 102, 255, 0.1);
}

.eye-icon {
    width: 20px;
    height: 20px;
}

.agreement {
    font-size: 14px;
    color: #666;
}

.checkbox-label {
    display: flex;
    align-items: center;
    gap: 8px;
}

.link {
    color: #7B66FF;
    text-decoration: none;
    transition: color 0.3s;
}

.link:hover {
    color: #6B56FF;
}

.submit-btn {
    width: 100%;
    padding: 12px;
    background-color: #7B66FF;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s;
}

.submit-btn:hover:not(:disabled) {
    background-color: #6B56FF;
}

.submit-btn:disabled {
    background-color: #b2b2b2;
    cursor: not-allowed;
}

.bottom-links {
    text-align: center;
    font-size: 14px;
    color: #666;
}

.login-link {
    color: #7B66FF;
    text-decoration: none;
    margin-left: 4px;
    transition: color 0.3s;
}

.login-link:hover {
    color: #6B56FF;
}

.alternative-register {
    text-align: center;
    margin-top: 16px;
}

.email-register {
    color: #666;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.3s;
}

.email-register:hover {
    color: #7B66FF;
}
</style>